package com.softao.ming.gde.internal.ui.popupmenus;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.softao.ming.gde.internal.ui.wizard.export.ExportGdeApplicationModuleWizard;

/**
 * 
 */
public class BuildGdeApplicationAction implements IObjectActionDelegate{
	private Shell mShell;
	private ISelection mSelection;
	
	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		mShell = targetPart.getSite().getShell();
	}

	private void buildProject(IProject project) throws CoreException {
		ExportGdeApplicationModuleWizard wizard = new ExportGdeApplicationModuleWizard(project);
		WizardDialog dialog = new WizardDialog(mShell, wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();
	}
	
	@Override
	public void run(IAction action) {
		if (mSelection instanceof IStructuredSelection) {
			Object[] elems = ((IStructuredSelection) mSelection).toArray();
			for (int i = 0; i < elems.length; i++) {
				Object elem = elems[i];
				IProject project = null;

				if (elem instanceof IFile) {
					IFile file = (IFile) elem;
					project = file.getProject();
				} else if (elem instanceof IProject) {
					project = (IProject) elem;
				} else if (elem instanceof IJavaProject) {
					project = ((IJavaProject) elem).getProject();
				}
				if (project != null) {
					try {
						buildProject(project);
					} catch (CoreException e) {
						e.printStackTrace();
					}
					return;
				}
			}
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		mSelection = selection;
	}
}
